package com.andreas.message;

import com.andreas.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 * 描述：消息接受1
 */
public class MessageReceiver3 {
    static int i = 1; // 记录执行次数

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        // 声明队列（此处为消费者，不是声明创建队列，而且获取，二者代码相同）出餐口排队
        channel.queueDeclare("test_work_queue", false, false, false, null);
        // 表示的是能者多劳
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("【顾客1】吃掉 " + msg + " ! 共吃【" + i++ + "】串");
                // 撸一会，有延迟
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume("test_work_queue", false, defaultConsumer);
    }
}
